package com.service.impl;

import com.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;

@Service
@Configuration
public class MailServiceImpl implements MailService {

    @Value("${spring.mail.username}")
    private String sendAddress;

    @Autowired
    private JavaMailSender mailSender;

    @Override
    public void sendSimpleMail() throws Exception {

        //获取简单邮件实例
        SimpleMailMessage message = new SimpleMailMessage();

        //发送邮件的地址
//        message.setFrom("makeyyoung@163.com");
        message.setFrom(sendAddress);
        //接收邮件的地址
        message.setTo("149430860@qq.com");
        //邮件主题(标题)
        message.setSubject("java mail测试");
        //邮件内容
        message.setText("喂, 喂, 试音~");
        //抄送
        message.setCc(sendAddress);
        //发送时间
//        message.setSentDate(new Date());

        mailSender.send(message);
    }

    @Override
    public void sendMailWithFile() throws Exception {

        //邮件对象
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        //邮件助手
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);

        helper.setFrom(sendAddress);
        helper.setTo("149430860@qq.com");
        helper.setSubject("测试, 我带了礼物!");
        helper.setText("<html><body><h1>哈哈哈! 没想到吧!</h1></body></html>");
//        helper.setCc(sendAddress);
        File file1 = new File("D:\\JT44\\009workspaces\\hetao.jpg");
        helper.addAttachment(file1.getName(), file1);

        mailSender.send(mimeMessage);
    }

    @Override
    public void sendActiveMail(String email, String code) throws Exception {

        SimpleMailMessage message = new SimpleMailMessage();

        message.setFrom(sendAddress);
        message.setTo(email);
        message.setSubject("爱旅行账户激活");
        message.setText("请点击以下地址激活您的账户:" + code);

        mailSender.send(message);
    }
}














